var express = require('express');
var swig = require('swig');
var bodyParser = require('body-parser');
var path = require('path');
var Cookies = require('cookies');
var app = express();
var db = require('./libs/mysql');
//静态文件托管
app.use( '/public', express.static( __dirname + '/public') );
app.use(express.static(path.join(__dirname, 'public')));



//模板
app.engine('html', swig.renderFile);
app.set('views', './views');
app.set('view engine', 'html');
//在开发过程中，需要取消模板缓存
swig.setDefaults({cache: false});
//body数据
app.use( bodyParser.urlencoded({extended: true}) );

//加载ueditor 模块
var ueditor = require("ueditor");

//使用模块
app.use("/ueditor/ue", ueditor(path.join(__dirname, 'public'), function (req, res, next) {
    // ueditor 客户发起上传图片请求
    if (req.query.action === 'uploadimage') {
        var foo = req.ueditor;

        var imgname = req.ueditor.filename;

        var img_url = '/images/ueditor/';
        res.ue_up(img_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
        res.setHeader('Content-Type', 'text/html');//IE8下载需要设置返回头尾text/html 不然json返回文件会被直接下载打开
    }
    //  客户端发起图片列表请求
    else if (req.query.action === 'listimage') {
        var dir_url = '/images/ueditor/';
        res.ue_list(dir_url); // 客户端会列出 dir_url 目录下的所有图片
    }
    // 客户端发起其它请求
    else {
        // console.log('config.json')
        res.setHeader('Content-Type', 'application/json');
        res.redirect('/ueditor/jsp/config.json');
    }
}));



//设置cookie
app.use(function (req,res,next) {
    req.cookies=new Cookies(req,res);
    req.userInfo = {};
    if (req.cookies.get('userInfo')) {
        try {
            req.userInfo = JSON.parse(req.cookies.get('userInfo'));
            req.userInfo.nickname = unescape(req.userInfo.nickname);
            //获取当前登录用户的类型，是否是管理员
            db.query(`SELECT * FROM user WHERE id = '${req.userInfo.id}'`,(err,data)=>{
                req.userInfo.isAdmin = data[0].isAdmin;
                next();
            });
        }catch(e){
            next();
        }
    }else {
        next();
    }
})

app.use('/',require('./route/web/index/index'));
app.use('/admin',require('./route/admin/index/index'));
app.get('*', function(req, res){
    res.render('404.html', {
        title: 'No Found'
    })
});
app.listen(168, function () {
    console.log('运行成功 : 168');
});